package com.example.demo.advice;

import com.sun.deploy.util.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Date;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalBindingHandler {

    @Data
    public static class ResultVo {
        private String message;
        private String code;
        private Date requestTime;
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultVo BindingResultHandler(BindException bindException){
        ResultVo resultVo = new ResultVo();

        resultVo.setCode("-1");
        resultVo.setRequestTime(new Date());

        String msg = StringUtils.join(bindException.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()),",");

        resultVo.setMessage(String.format("请求参数校验错误，来自：[%s]",msg));

        return resultVo;
    }
}
